//
//  FX7FilterEffect.swift
//  YCCamera
//
//  Created by YCCamera Team on 2024/11/10.
//  实现 fx7 滤镜效果（基于 PNG LUT + 多重效果组合）
//

import Foundation
import CoreImage
import UIKit
import Metal
import MetalKit

/// FX7 滤镜效果（Metal + CoreImage 混合实现）
/// 优先使用 Metal GPU 加速，失败时回退到 CoreImage
/// 基于 camera_fx7.json 配置的 PNG LUT 滤镜
class FX7FilterEffect: BaseFilterEffect {
    
    // MARK: - Properties
    
    /// LUT PNG 图像名称
    private let lutImageName = "camera_lut_fx7"
    
    /// 效果参数（从 camera_fx7.json 读取）
    private struct EffectParams {
        // MGLutEffect
        static let lutStrength: Float = 0.82
        
        // MGHighSoftLightEffect（高光柔光）- 严格按照 JSON 配置
        static let highlightRate: CGFloat = 0.57    // 高光强度（JSON 原值）
        static let softRate: CGFloat = 0.42          // 柔化程度（JSON 原值）
        static let lightRate: CGFloat = 0.147        // 亮度提升（JSON 原值）
        
        // MGSharpenEffect（锐化）
        static let sharpness: CGFloat = 0.11         // 锐化强度
        // static let blurAmount: CGFloat = 0.2      // 模糊量（保留，暂未使用）
        
        // MGRGBNoiseV2Effect（RGB 噪点）
        // static let noiseMode: Int = 1             // 噪点模式（保留，暂未使用）
        // static let noiseSpeed: CGFloat = 0.53     // 噪点速度（保留，暂未使用）
        static let noiseIntensity: CGFloat = 0.56    // 噪点强度
        
        // MGGaussianEffect（高斯柔化）
        static let gaussianStrength: CGFloat = 0.006 // 柔化强度
        
        // MGTiltShiftEffect（移轴效果）
        // static let tiltShiftV: CGFloat = 0.002    // 垂直参数（保留，暂未使用）
        static let tiltShiftR: CGFloat = 0.59        // 范围参数
    }
    
    // MARK: - Metal Resources
    
    /// Metal 设备
    private static let device = MTLCreateSystemDefaultDevice()
    
    /// Metal 命令队列
    private static let commandQueue = device?.makeCommandQueue()
    
    /// Metal 计算管道
    private static var pipelineState: MTLComputePipelineState?
    
    /// LUT 纹理（GPU 缓存）
    private static var lutTexture: MTLTexture?
    
    /// 纹理加载器
    private static let textureLoader: MTKTextureLoader? = {
        guard let device = device else { return nil }
        return MTKTextureLoader(device: device)
    }()
    
    /// Metal 初始化标志
    private static var metalInitialized = false
    
    // MARK: - CoreImage Cache
    
    /// 缓存的 ColorCube 数据（CoreImage 后备方案）
    private static var cachedCubeData: Data?
    private static var cacheInitialized = false
    
    // MARK: - Initialization
    
    override init() {
        super.init()
        
        // 初始化 Metal 资源（只执行一次）
        if !Self.metalInitialized {
            Self.metalInitialized = true
            Self.setupMetal()
        }
    }
    
    /// 设置 Metal 资源
    private static func setupMetal() {
        guard let device = device else {
            print("⚠️ FX7: Metal 设备不可用，将使用 CoreImage 后备方案")
            return
        }
        
        print("🔧 FX7: 开始初始化 Metal 资源...")
        
        // 1. 创建计算管道
        do {
            guard let library = device.makeDefaultLibrary() else {
                print("❌ FX7: 无法创建 Metal Library")
                return
            }
            
            guard let function = library.makeFunction(name: "fx7LUTFilter") else {
                print("❌ FX7: 无法找到着色器函数 fx7LUTFilter")
                return
            }
            
            pipelineState = try device.makeComputePipelineState(function: function)
            print("✅ FX7: Metal 管道创建成功")
            
        } catch {
            print("❌ FX7: 创建 Metal 管道失败: \(error)")
            return
        }
        
        // 2. 加载 LUT 纹理
        loadLUTTexture()
    }
    
    /// 加载 LUT 纹理到 GPU
    private static func loadLUTTexture() {
        guard let textureLoader = textureLoader else {
            print("❌ FX7: TextureLoader 不可用")
            return
        }
        
        guard let image = UIImage(named: "camera_lut_fx7"),
              let cgImage = image.cgImage else {
            print("❌ FX7: 无法加载 LUT PNG: camera_lut_fx7")
            return
        }
        
        do {
            let options: [MTKTextureLoader.Option: Any] = [
                .SRGB: false,  // 关键：不使用 sRGB，保持线性颜色空间
                .generateMipmaps: false
            ]
            
            lutTexture = try textureLoader.newTexture(cgImage: cgImage, options: options)
            print("✅ FX7: LUT 纹理加载成功 (\(lutTexture!.width)×\(lutTexture!.height))")
            
        } catch {
            print("❌ FX7: LUT 纹理加载失败: \(error)")
        }
    }
    
    // MARK: - Filter Application
    
    override func apply(to image: CIImage, with parameters: FilterParameters, context: CIContext) -> CIImage? {
        var outputImage = image
        
        // 按照 camera_fx7.json 中的顺序应用效果
        // "filters": ["MGTiltShiftEffect", "MGHighSoftLightEffect", "MGLutEffect", 
        //             "MGSharpenEffect", "MGRGBNoiseV2Effect", "MGGaussianEffect"]
        
        // 1. MGTiltShiftEffect（移轴效果）
        outputImage = applyTiltShiftEffect(to: outputImage) ?? outputImage
        
        // 2. MGHighSoftLightEffect（高光柔光）
        outputImage = applyHighSoftLightEffect(to: outputImage) ?? outputImage
        
        // 3. MGLutEffect（LUT 颜色映射）- 优先使用 Metal
        if let device = Self.device,
           let commandQueue = Self.commandQueue,
           let pipelineState = Self.pipelineState,
           let lutTexture = Self.lutTexture,
           let metalResult = applyMetalLUT(to: outputImage,
                                          device: device,
                                          commandQueue: commandQueue,
                                          pipelineState: pipelineState,
                                          lutTexture: lutTexture,
                                          context: context) {
            outputImage = metalResult
        } else {
            outputImage = applyLUTEffect(to: outputImage) ?? outputImage
        }
        
        // 4. MGSharpenEffect（锐化）
        outputImage = applySharpenEffect(to: outputImage) ?? outputImage
        
        // 5. MGRGBNoiseV2Effect（RGB 噪点）
        outputImage = applyRGBNoiseV2Effect(to: outputImage) ?? outputImage
        
        // 6. MGGaussianEffect（高斯柔化）
        outputImage = applyGaussianEffect(to: outputImage) ?? outputImage
        
        // 最终裁剪到原始边界
        outputImage = outputImage.cropped(to: image.extent)
        
        return outputImage
    }
    
    override func supportsMetalAcceleration() -> Bool {
        return Self.pipelineState != nil && Self.lutTexture != nil
    }
    
    // MARK: - Metal Processing
    
    /// 使用 Metal 应用 LUT（高性能 GPU 加速）
    private func applyMetalLUT(to image: CIImage,
                              device: MTLDevice,
                              commandQueue: MTLCommandQueue,
                              pipelineState: MTLComputePipelineState,
                              lutTexture: MTLTexture,
                              context: CIContext) -> CIImage? {
        
        let extent = image.extent
        let width = Int(extent.width)
        let height = Int(extent.height)
        
        print("🎨 FX7 Metal处理 - 输入尺寸: \(width) x \(height)")
        
        // 创建纹理描述符
        let descriptor = MTLTextureDescriptor.texture2DDescriptor(
            pixelFormat: .rgba16Float,
            width: width,
            height: height,
            mipmapped: false
        )
        descriptor.usage = [.shaderRead, .shaderWrite]
        
        guard let inputTexture = device.makeTexture(descriptor: descriptor),
              let outputTexture = device.makeTexture(descriptor: descriptor) else {
            return nil
        }
        
        // 将 CIImage 渲染到输入纹理
        context.render(image,
                      to: inputTexture,
                      commandBuffer: nil,
                      bounds: extent,
                      colorSpace: CGColorSpaceCreateDeviceRGB())
        
        // 创建命令缓冲区
        guard let commandBuffer = commandQueue.makeCommandBuffer(),
              let computeEncoder = commandBuffer.makeComputeCommandEncoder() else {
            return nil
        }
        
        // 设置管道和参数
        computeEncoder.setComputePipelineState(pipelineState)
        computeEncoder.setTexture(inputTexture, index: 0)
        computeEncoder.setTexture(outputTexture, index: 1)
        computeEncoder.setTexture(lutTexture, index: 2)
        
        var strength = EffectParams.lutStrength
        computeEncoder.setBytes(&strength, length: MemoryLayout<Float>.size, index: 0)
        
        // 计算线程组大小
        let threadGroupSize = MTLSize(width: 16, height: 16, depth: 1)
        let threadGroups = MTLSize(
            width: (width + threadGroupSize.width - 1) / threadGroupSize.width,
            height: (height + threadGroupSize.height - 1) / threadGroupSize.height,
            depth: 1
        )
        
        // 执行计算
        computeEncoder.dispatchThreadgroups(threadGroups, threadsPerThreadgroup: threadGroupSize)
        computeEncoder.endEncoding()
        
        // 提交命令
        commandBuffer.commit()
        
        // 注意：这里必须等待完成，因为 CIImage 需要从纹理读取数据
        // 但这会导致 CPU 等待，是性能瓶颈
        commandBuffer.waitUntilCompleted()
        
        // 将输出纹理转换为 CIImage
        let result = CIImage(mtlTexture: outputTexture, options: [.colorSpace: CGColorSpaceCreateDeviceRGB()])
        print("🎨 FX7 Metal处理 - 输出尺寸: \(result?.extent.width ?? 0) x \(result?.extent.height ?? 0)")
        return result
    }
    
    // MARK: - CoreImage LUT (Fallback)
    
    /// 应用 LUT 效果（CoreImage 实现，用于 Metal 不可用时的后备）
    private func applyLUTEffect(to image: CIImage) -> CIImage? {
        // 使用缓存的 ColorCube 数据（避免每帧重复提取）
        let cubeData: Data
        
        if !Self.cacheInitialized {
            // 首次加载，提取 ColorCube 数据
            guard let lutImage = UIImage(named: lutImageName),
                  let cgImage = lutImage.cgImage else {
                print("❌ FX7: 无法加载 LUT 图片")
                return image
            }
            
            guard let extractedData = extractColorCubeData(from: cgImage) else {
                print("❌ FX7: 无法提取 ColorCube 数据")
                return image
            }
            
            Self.cachedCubeData = extractedData
            Self.cacheInitialized = true
            cubeData = extractedData
            print("✅ FX7: ColorCube 数据已缓存")
        } else {
            // 使用缓存数据
            guard let cached = Self.cachedCubeData else {
                print("❌ FX7: 缓存数据不可用")
                return image
            }
            cubeData = cached
        }
        
        // 使用 CIColorCube 应用 LUT
        guard let colorCubeFilter = CIFilter(name: "CIColorCube") else {
            print("❌ FX7: 无法创建 CIColorCube 滤镜")
            return image
        }
        
        colorCubeFilter.setValue(image, forKey: kCIInputImageKey)
        colorCubeFilter.setValue(64, forKey: "inputCubeDimension")
        colorCubeFilter.setValue(cubeData, forKey: "inputCubeData")
        
        guard let outputImage = colorCubeFilter.outputImage else {
            return image
        }
        
        // 应用强度混合
        if EffectParams.lutStrength < 1.0 {
            // 混合原图和LUT图
            guard let blendFilter = CIFilter(name: "CIBlendWithMask") else {
                return outputImage
            }
            
            // 创建一个均匀的 mask（alpha）
            let maskImage = CIImage(color: CIColor(red: 1, green: 1, blue: 1, alpha: CGFloat(EffectParams.lutStrength)))
                .cropped(to: image.extent)
            
            blendFilter.setValue(outputImage, forKey: kCIInputImageKey)
            blendFilter.setValue(image, forKey: kCIInputBackgroundImageKey)
            blendFilter.setValue(maskImage, forKey: kCIInputMaskImageKey)
            
            return blendFilter.outputImage ?? outputImage
        }
        
        return outputImage
    }
    
    /// 从 PNG LUT 图像中提取 ColorCube 数据
    /// PNG 格式：512×512，8×8 布局，64³ 精度
    private func extractColorCubeData(from cgImage: CGImage) -> Data? {
        let width = cgImage.width
        let height = cgImage.height
        
        guard width == 512 && height == 512 else {
            print("❌ FX7: LUT 图片尺寸不正确 (\(width)×\(height))，应该是 512×512")
            return nil
        }
        
        // 创建位图上下文
        guard let context = CGContext(
            data: nil,
            width: width,
            height: height,
            bitsPerComponent: 8,
            bytesPerRow: width * 4,
            space: CGColorSpaceCreateDeviceRGB(),
            bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
        ) else {
            print("❌ FX7: 无法创建 CGContext")
            return nil
        }
        
        // 绘制图像
        context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
        
        guard let pixelData = context.data else {
            print("❌ FX7: 无法获取像素数据")
            return nil
        }
        
        // 提取 ColorCube 数据（64×64×64）
        let dimension = 64
        let cubeSize = dimension * dimension * dimension * 4 // RGBA 分量数
        let cubeSizeInBytes = cubeSize * MemoryLayout<Float>.size // 字节数
        
        // 注释：64³ × 4 (RGBA) × 4 bytes/Float = 4,194,304 bytes
        
        var cubeData = Data(count: cubeSizeInBytes)
        let pixels = pixelData.bindMemory(to: UInt8.self, capacity: width * height * 4)
        
        let result = cubeData.withUnsafeMutableBytes { (rawPtr: UnsafeMutableRawBufferPointer) -> Bool in
            guard let baseAddress = rawPtr.baseAddress else {
                print("❌ FX7: cubeBuffer baseAddress 为空")
                return false
            }
            
            let cubeBuffer = baseAddress.assumingMemoryBound(to: Float.self)
            
            for blueIndex in 0..<dimension {
                for greenIndex in 0..<dimension {
                    for redIndex in 0..<dimension {
                        // 计算 PNG 中的位置
                        let blockX = (blueIndex % 8) * dimension
                        let blockY = (blueIndex / 8) * dimension
                        let x = blockX + redIndex
                        let y = blockY + greenIndex
                        
                        // 边界检查
                        guard x < width && y < height else {
                            print("❌ FX7: 坐标越界 x=\(x), y=\(y)")
                            return false
                        }
                        
                        // 读取像素值
                        let pixelIndex = (y * width + x) * 4
                        guard pixelIndex + 3 < width * height * 4 else {
                            print("❌ FX7: pixelIndex 越界: \(pixelIndex)")
                            return false
                        }
                        
                        let r = Float(pixels[pixelIndex]) / 255.0
                        let g = Float(pixels[pixelIndex + 1]) / 255.0
                        let b = Float(pixels[pixelIndex + 2]) / 255.0
                        let a = Float(pixels[pixelIndex + 3]) / 255.0
                        
                        // 写入 ColorCube 数据
                        let cubeIndex = (blueIndex * dimension * dimension + greenIndex * dimension + redIndex) * 4
                        guard cubeIndex + 3 < cubeSize else {
                            print("❌ FX7: cubeIndex 越界: \(cubeIndex)")
                            return false
                        }
                        
                        cubeBuffer[cubeIndex] = r
                        cubeBuffer[cubeIndex + 1] = g
                        cubeBuffer[cubeIndex + 2] = b
                        cubeBuffer[cubeIndex + 3] = a
                    }
                }
            }
            
            return true
        }
        
        guard result else {
            print("❌ FX7: ColorCube 数据提取失败")
            return nil
        }
        
        print("✅ FX7: ColorCube 数据提取成功 (\(dimension)³)")
        return cubeData
    }
    
    // MARK: - Individual Effects Implementation
    
    /// 1. MGTiltShiftEffect - 移轴效果（模拟浅景深）
    private func applyTiltShiftEffect(to image: CIImage) -> CIImage? {
        // 移轴效果：中心区域清晰，边缘模糊，模拟镜头移轴效果
        // v = 0.002（非常轻微的效果）
        // r = 0.59（模糊范围）
        
        let imageHeight = image.extent.height
        let blurRadius = EffectParams.tiltShiftR * 10.0 // 模糊半径
        
        // 创建径向渐变遮罩（中心清晰，边缘模糊）
        let gradientFilter = CIFilter(name: "CIRadialGradient")
        gradientFilter?.setValue(CIVector(x: image.extent.midX, y: image.extent.midY), forKey: "inputCenter")
        gradientFilter?.setValue(imageHeight * 0.3, forKey: "inputRadius0")
        gradientFilter?.setValue(imageHeight * EffectParams.tiltShiftR, forKey: "inputRadius1")
        gradientFilter?.setValue(CIColor.white, forKey: "inputColor0")
        gradientFilter?.setValue(CIColor.black, forKey: "inputColor1")
        
        guard let maskImage = gradientFilter?.outputImage?.cropped(to: image.extent) else {
            return image
        }
        
        // 应用高斯模糊
        guard let blurFilter = CIFilter(name: "CIGaussianBlur") else { return image }
        blurFilter.setValue(image, forKey: kCIInputImageKey)
        blurFilter.setValue(blurRadius, forKey: kCIInputRadiusKey)
        
        guard let blurredImage = blurFilter.outputImage?.cropped(to: image.extent) else {
            return image
        }
        
        // 使用遮罩混合清晰和模糊图像
        guard let blendFilter = CIFilter(name: "CIBlendWithMask") else { return image }
        blendFilter.setValue(image, forKey: kCIInputImageKey)
        blendFilter.setValue(blurredImage, forKey: kCIInputBackgroundImageKey)
        blendFilter.setValue(maskImage, forKey: kCIInputMaskImageKey)
        
        return blendFilter.outputImage?.cropped(to: image.extent)
    }
    
    /// 2. MGHighSoftLightEffect - 高光柔光效果
    private func applyHighSoftLightEffect(to image: CIImage) -> CIImage? {
        var output = image
        
        // 1. 提升整体亮度（lightRate: 0.147）
        if let exposureFilter = CIFilter(name: "CIExposureAdjust") {
            exposureFilter.setValue(output, forKey: kCIInputImageKey)
            exposureFilter.setValue(EffectParams.lightRate, forKey: kCIInputEVKey)
            if let result = exposureFilter.outputImage {
                output = result
            }
        }
        
        // 2. 增强高光（highlightRate: 0.57）
        if let highlightFilter = CIFilter(name: "CIHighlightShadowAdjust") {
            highlightFilter.setValue(output, forKey: kCIInputImageKey)
            highlightFilter.setValue(EffectParams.highlightRate, forKey: "inputHighlightAmount")
            highlightFilter.setValue(0.0, forKey: "inputShadowAmount")
            if let result = highlightFilter.outputImage {
                output = result
            }
        }
        
        // 3. 轻微柔化（softRate: 0.42）
        if EffectParams.softRate > 0 {
            let blurRadius = EffectParams.softRate * 0.5
            if let blurFilter = CIFilter(name: "CIGaussianBlur") {
                blurFilter.setValue(output, forKey: kCIInputImageKey)
                blurFilter.setValue(blurRadius, forKey: kCIInputRadiusKey)
                
                if let blurred = blurFilter.outputImage?.cropped(to: image.extent) {
                    // 混合原图和模糊图（柔光效果）
                    let alpha = EffectParams.softRate * 0.3
                    if let blendFilter = CIFilter(name: "CISourceOverCompositing") {
                        blendFilter.setValue(blurred, forKey: kCIInputImageKey)
                        blendFilter.setValue(output, forKey: kCIInputBackgroundImageKey)
                        if let blended = blendFilter.outputImage {
                            output = blended.applyingFilter("CIColorMatrix", parameters: [
                                "inputRVector": CIVector(x: 1, y: 0, z: 0, w: 0),
                                "inputGVector": CIVector(x: 0, y: 1, z: 0, w: 0),
                                "inputBVector": CIVector(x: 0, y: 0, z: 1, w: 0),
                                "inputAVector": CIVector(x: 0, y: 0, z: 0, w: alpha),
                                "inputBiasVector": CIVector(x: 0, y: 0, z: 0, w: 1 - alpha)
                            ])
                        }
                    }
                }
            }
        }
        
        return output.cropped(to: image.extent)
    }
    
    /// 4. MGSharpenEffect - 锐化效果
    private func applySharpenEffect(to image: CIImage) -> CIImage? {
        guard let sharpenFilter = CIFilter(name: "CISharpenLuminance") else {
            return image
        }
        
        sharpenFilter.setValue(image, forKey: kCIInputImageKey)
        sharpenFilter.setValue(EffectParams.sharpness, forKey: kCIInputSharpnessKey)
        
        return sharpenFilter.outputImage?.cropped(to: image.extent)
    }
    
    /// 5. MGRGBNoiseV2Effect - RGB 噪点效果（胶片颗粒感）
    private func applyRGBNoiseV2Effect(to image: CIImage) -> CIImage? {
        // 生成动态随机噪点（每帧不同）
        guard let noiseGenerator = CIFilter(name: "CIRandomGenerator") else {
            return image
        }
        
        guard var noiseImage = noiseGenerator.outputImage else {
            return image
        }
        
        // 关键：使用时间戳偏移，让噪点每帧都不同（动态效果）
        let timeOffset = CGAffineTransform(translationX: CGFloat(arc4random_uniform(1000)),
                                          y: CGFloat(arc4random_uniform(1000)))
        noiseImage = noiseImage.transformed(by: timeOffset)
        
        // 裁剪噪点到图像尺寸
        noiseImage = noiseImage.cropped(to: image.extent)
        
        // 模糊噪点以形成胶片颗粒
        // intensity: 0.56 意味着中等强度的噪点
        if let blurFilter = CIFilter(name: "CIGaussianBlur") {
            blurFilter.setValue(noiseImage, forKey: kCIInputImageKey)
            // 根据 intensity 0.56 调整：适中的颗粒大小
            blurFilter.setValue(1.2, forKey: kCIInputRadiusKey)
            if let blurred = blurFilter.outputImage?.cropped(to: image.extent) {
                noiseImage = blurred
            }
        }
        
        // 调整噪点对比度和亮度（模拟胶片颗粒的明暗对比）
        // intensity: 0.56 表示中等强度，需要适度的对比度
        if let colorControlsFilter = CIFilter(name: "CIColorControls") {
            colorControlsFilter.setValue(noiseImage, forKey: kCIInputImageKey)
            colorControlsFilter.setValue(1.6, forKey: kCIInputContrastKey)  // 中等对比度
            colorControlsFilter.setValue(0.4, forKey: kCIInputBrightnessKey) // 适度亮度
            colorControlsFilter.setValue(1.0, forKey: kCIInputSaturationKey) // 保持饱和度，让颗粒有色彩
            if let adjusted = colorControlsFilter.outputImage {
                noiseImage = adjusted
            }
        }
        
        // 调整噪点强度和颜色（RGB 噪点 V2 - 彩色胶片颗粒）
        // mode: 1, intensity: 0.56 - 表示彩色胶片颗粒，中等强度
        if let colorMatrixFilter = CIFilter(name: "CIColorMatrix") {
            colorMatrixFilter.setValue(noiseImage, forKey: kCIInputImageKey)
            // intensity: 0.56 转换为合适的 scale
            let scale = CGFloat(EffectParams.noiseIntensity) * 0.20
            
            // RGB 噪点 V2：轻微的色彩分离，模拟胶片RGB层
            colorMatrixFilter.setValue(CIVector(x: scale * 1.15, y: 0, z: 0, w: 0), forKey: "inputRVector")
            colorMatrixFilter.setValue(CIVector(x: 0, y: scale * 0.85, z: 0, w: 0), forKey: "inputGVector")
            colorMatrixFilter.setValue(CIVector(x: 0, y: 0, z: scale * 1.10, w: 0), forKey: "inputBVector")
            colorMatrixFilter.setValue(CIVector(x: 0, y: 0, z: 0, w: 1), forKey: "inputAVector")
            
            // 轻微的暖色调偏移（胶片特征）
            colorMatrixFilter.setValue(CIVector(x: 0.01, y: 0, z: 0.012, w: 0), forKey: "inputBiasVector")
            
            if let adjustedNoise = colorMatrixFilter.outputImage {
                noiseImage = adjustedNoise
            }
        }
        
        // 使用 Overlay 混合模式，让颗粒更自然地融入图像，并保留色彩
        guard let blendFilter = CIFilter(name: "CIOverlayBlendMode") else {
            // 如果 Overlay 不可用，使用 Screen 模式（提亮效果）
            guard let fallbackFilter = CIFilter(name: "CIScreenBlendMode") else {
                return image
            }
            fallbackFilter.setValue(noiseImage, forKey: kCIInputImageKey)
            fallbackFilter.setValue(image, forKey: kCIInputBackgroundImageKey)
            return fallbackFilter.outputImage?.cropped(to: image.extent)
        }
        
        blendFilter.setValue(noiseImage, forKey: kCIInputImageKey)
        blendFilter.setValue(image, forKey: kCIInputBackgroundImageKey)
        
        return blendFilter.outputImage?.cropped(to: image.extent)
    }
    
    /// 6. MGGaussianEffect - 高斯柔化效果
    private func applyGaussianEffect(to image: CIImage) -> CIImage? {
        // 非常轻微的高斯模糊（strength: 0.006）
        let radius = EffectParams.gaussianStrength * 10.0 // 约 0.06 像素
        
        guard let blurFilter = CIFilter(name: "CIGaussianBlur") else {
            return image
        }
        
        blurFilter.setValue(image, forKey: kCIInputImageKey)
        blurFilter.setValue(radius, forKey: kCIInputRadiusKey)
        
        return blurFilter.outputImage?.cropped(to: image.extent)
    }
}

